// ==UserScript==
// @name           	备注插件
// @version        	1.2	
// @author			金狮足球俱乐部(club ID:4769087)
// @include			https://trophymanager.com/players/*
// @include			https://fb.trophymanager.com/players/*
// @include			https://trophymanager.com/transfer/*
// @include         https://fb.trophymanager.com/transfer/*
// @require         https://code.jquery.com/jquery-3.6.0.min.js
// @downloadURL     https://gitee.com/trophymanagerCN/tmjs/raw/master/note/%E5%A4%87%E6%B3%A8%E6%8F%92%E4%BB%B6.user.js
// @updateURL       https://gitee.com/trophymanagerCN/tmjs/raw/master/note/%E5%A4%87%E6%B3%A8%E6%8F%92%E4%BB%B6.meta.js
// ==/UserScript==
window.saveNote = function (playerId) {
    var newNote = $('#noteEditor').val();
    localStorage.setItem('playerNotes_' + playerId, newNote);
    $('#notesPopup').remove();
}
var notesConfig = {
    sectionId: 'notesSection',
    areaId: 'notesArea',
    saveBtnId: 'saveNotesButton',
    statusId: 'saveStatusMessage'
};
var transferList = document.getElementById('transfer_list');
function handleTransferPage() {
    var retryCount = 0;
    var maxRetries = 2;
    var retryInterval = 2000;
    function safeObserve() {
        var transferList = document.querySelector('#transfer_list_main .list-container');
        if (!transferList) {
            if (retryCount < maxRetries) {
                retryCount++;
                console.log('正在等待转会列表加载... 重试次数:', retryCount);
                setTimeout(safeObserve, retryInterval);
                return;
            }
            console.error('转会列表加载失败：请确认当前页面包含球员列表');
            return;
        }
        if (window.transferListObserver) {
            window.transferListObserver.disconnect();
        }

        window.transferListObserver = new MutationObserver(function () {
            checkAllNotes();
        }).observe(transferList, {
            childList: true,
            subtree: true
        });
    }
    setTimeout(safeObserve, 3000);
    setInterval(checkAllNotes, 1000);
    function checkAllNotes() {
        $('#transfer_list .player_name a').each(function () {
            var playerId = getPlayerId(this);
            if (playerId && localStorage.getItem('playerNotes_' + playerId)) {
                createNoteIndicator(playerId);
            }
        });
    }
    function getPlayerId(element) {
        try {
            return $(element).attr('href').match(/\d+/)[0];
        } catch (e) {
            console.warn('无法获取球员ID:', element);
            return null;
        }
    }
    function createNoteIndicator(playerId) {
        var $row = $('#transfer_list a[href*="/players/' + playerId + '"]').closest('tr');
        if ($row.length) {
            var $nameLink = $row.find('.player_name a');
            if (!$nameLink.next('.note-indicator').length) {
                $nameLink.after(
                    '<div class="note-indicator" style="margin-left:8px;cursor:pointer;' +
                    'color:white!important;font-weight:bold;display:inline-block;">[N]</div>'
                );
            }
        }
    }
    function toggleNotesPopup(playerId) {
        var notes = localStorage.getItem('playerNotes_' + playerId) || '';
        var popupHTML = '<div id="notesPopup" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);'
            + 'background:#2d2d2d;padding:4px;border:1px solid #555;z-index:9999;max-width:300px;color:#fff;'  // 减少内边距和边框
            + 'backdrop-filter: blur(2px);min-width:220px;max-height:85vh;overflow:hidden;">'  // 隐藏滚动条
            + '<textarea id="noteEditor" style="width:100%;min-height:50px;margin-bottom:6px;'
            + 'background:#6C9922;color:#fff;border:1px solid #666;scrollbar-width:none;">' + notes + '</textarea>'  // 修改背景色
            + '<div style="display:flex;gap:6px;flex-wrap:wrap;">'
            + '<button class="save-note-btn" data-playerid="' + playerId + '" class="button" style="padding:4px 10px;background:#6C9922;color:#fff;">保存笔记</button>'
            + '</div>';
        $('body').append(popupHTML).on('click', function (e) {
            if (!$(e.target).closest('#notesPopup').length) {
                $('#notesPopup').remove();
            }
        });
    }
    $('.transfer_list .flag-img-am').each(function () {
        var playerId = $(this).attr('href').match(/\d+/)[0];
        var notes = localStorage.getItem('playerNotes_' + playerId);
        if (notes) {
            createNoteIndicator(playerId);
            console.log('球员ID:', playerId, '笔记内容:', notes);
        } else {
            console.log('球员ID:', playerId, '没找到相关笔记');
        }
    });
    $(document).on('click', '.note-indicator', function () {
        var playerId = $(this).closest('tr').find('.player_name a').attr('href').match(/\d+/)[0];
        toggleNotesPopup(playerId);
    });
}

if (location.pathname.includes('/players/')) {
    $(".box_body").first().append([
        '<div id="', notesConfig.sectionId, '" class="notes-section" style="margin-left:6px">',
        '<textarea id="', notesConfig.areaId, '" class="notes-area" style="background-color:transparent!important"></textarea>',
        '<button id="', notesConfig.saveBtnId, '" class="button" style="width:80px;padding:0">保存笔记</button>',
        '<div id="', notesConfig.statusId, '" style="color:#4CAF50;margin-top:5px;display:none"></div>',
        '</div>'
    ].join(''));
}
function saveNote(playerId) {
    var newNote = $('#noteEditor').val();
    localStorage.setItem('playerNotes_' + playerId, newNote);
    $('#notesPopup').remove();
}
$(document).on('click', '.save-note-btn', function () {
    var playerId = $(this).data('playerid');
    window.saveNote(playerId);
});
$(document).ready(function () {
    function initPlayerPage() {
        var $area = $('#' + notesConfig.areaId);
        var playerID = (location.pathname.match(/\d+/g) || [])[0];

        $area.on('input', function () {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + 'px';
        });
        if (playerID) {
            $area.val(localStorage.getItem('playerNotes_' + playerID) || '');
            $area.trigger('input');
        }
    }
    if (location.href.indexOf('/transfer/') > -1) {
        setTimeout(handleTransferPage, 1000);
    } else {
        initPlayerPage();
    }
    $('#' + notesConfig.saveBtnId).click(function () {
        try {
            var playerID = (location.pathname.match(/\d+/g) || [])[0];
            if (!playerID) return;

            localStorage.setItem('playerNotes_' + playerID, $('#' + notesConfig.areaId).val());
            var $status = $('#' + notesConfig.statusId).stop().fadeIn().text("笔记保存成功！");
            setTimeout(function () { $status.fadeOut(); }, 2000);
        } catch (e) {
            console.error("保存失败:", e);
            $('#' + notesConfig.statusId).css('color', '#f44336').text("错误: " + e.message).fadeIn();
        }
    });
});